Accessibility

DRK Volume 4 Article

XRF (XML-RPC Framework) Component


If you're a ColdFusion MX developer, web services have been on your radar for at least a year or two. You've heard the hype and, in a break from established patterns in the technology industry, you've even seen the hype realized in the elegance of ColdFusion MX's support for Simple Object Access Protocol (SOAP) and the growing popularity of RSS syndication. It's becoming increasingly common for even the most casual CF-powered site to expose data to tools other than web browsers.

For all the momentum behind ColdFusion-powered web services, however, something has been missing. There is a web services technology out there that is used daily by literally thousands of people—companies, hobbyists, and independent developers alike—a technology that is an integral part of the blogging phenomenon and the tools that power it. It's called XML-RPC. If you're as unfamiliar with it as the average ColdFusion developer, now is the time to catch up.

Think of XML-RPC (XML Remote Procedure Call) as SOAP's lightweight, counter-culture cousin. Created by UserLand Software in 1998, it is essentially a means of wrapping data in a basic XML envelope and passing that envelope around using HTTP. The best way to characterize the differences between SOAP and XML-RPC is to suggest that, if SOAP were a story, it would be richly detailed with a complex plot and sophisticated protagonists. XML-RPC, on the other hand, would be a few brief paragraphs that hit the high points and moved on.

It's precisely this no-nonsense approach to web services that has made XML-RPC so popular among small developers and open-source enthusiasts, including the folks working on blogging applications and other forms of next-generation "social software." The tremendously popular Blogger service uses XML-RPC to allow third-party interfaces and desktop applications to post new content and manage user accounts. Tools like Movable Type and JournURL automatically send XML-RPC requests to sites like Weblogs.com that provide update tracking services. And when you make an audio post to a site using AudBlog, you're using XML-RPC. In short, if your applications need to interoperate with web logs or the services that connect them, you need to support XML-RPC in your code.

Implementing XML-RPC

Implementing XML-RPC in ColdFusion has always been easier said than done. Although ColdFusion MX developers have enjoyed the ease with which SOAP services can be created, we've been pretty much on our own regarding XML-RPC. We've had to dig into the specification, absorb the details, and try to make sense of the scattered and usually outdated CF-related information that exists. Fortunately, those days are now over.

The XML-RPC Framework (XRF) for ColdFusion MX can create a web service based on XML-RPC as easily as one based on SOAP, using the same component mechanisms with which you're familiar. In fact, with minor modifications, existing ColdFusion MX web services can be retrofitted to support XML-RPC and SOAP simultaneously.

The XRF is made up of two small CFCs. The first (xmlrpc.cfc) is a bit of code that does the heavy lifting of translating XML-RPC data to and from native ColdFusion data structures. The second (xmlrpcservice.cfc) is a little more magical; it provides a wrapper for a SOAP-based service, allowing the same code to speak two different web service "languages." Changing one line of code and adding another is all it takes to get the new version of your web service up and running.

Installating the XRF

To install the XML-RPC Framework, place both CFCs wherever you normally store your components and then call them with a suitable path. As long as you keep xmlrpc.cfc and xmlrpcservice.cfc together, everything should work fine. However, make sure you suppress debugging output using the ColdFusion Administrator (or <cfsetting showdebugoutput="No">) because valid XML and random chunks of HTML-formatted debugging information do not mix.


Running Your First XML-RPC Service

Let's start with something simple. (We'll get into the minutiae later.) For example, date.cfc includes a method for setting the date:

<cfcomponent>
   <cffunction name="setDate" output="false" access="remote">
      <cfargument name="date" type="date" required="true" /> 
      <cfset var myResult = StructNew() />
      <cfset myResult.message = "the date has been set to #arguments.date#" /> 
      <cfset myResult.date = ParseDateTime(arguments.date) />
      <cfreturn myResult />
   </cffunction>
</cfcomponent>

As you can see, this code accepts a date value and returns a structure with two keys. Assuming you've placed the CFC in the root directory of your web server, you could call it like so:

http://yourserver/date.cfc?method=setDate&date=01/01/1999 

Let's see what you have to do to make the same CFC work with XML-RPC:

<cfcomponent extends="xmlrpcservice">
   <cffunction name="setDate" output="false" access="remote" xmlRpcAccess="true">
      <cfargument name="date" type="date" required="true" /> 
      <cfset var myResult = StructNew() />
      <cfset myResult.message = "the date has been set to #arguments.date#" /> 
      <cfset myResult.date = ParseDateTime(arguments.date) />
      <cfreturn myResult />
   </cffunction>
</cfcomponent>

That's it. You simply extend xmlrpcservice.cfc and set a single attribute on each cffunction tag that you'd like to expose using XML-RPC. To consume the new service, a developer on the other end would construct an XML-RPC request and send it to a URL like this:

http://yourserver/date.cfm?method=xmlrpc&paramNames=date 

The XRF handles all the details of parsing the incoming XML-RPC package into something that ColdFusion can understand, and subsequently translating the results back into XML. It even catches CFML errors and returns them to the client as properly formatted fault messages.

Testing Your XML-RPC Service

To make sure everything is working with your XRF-enabled component, you need to test it using an XML-RPC debugger. (I recommend the one provided by Dumpleton Software Consulting.)

Let's give it a try:

  1. Create a directory off your web server's root called rpctest.
  2. Save the sample files date.cfc, xmlrpc.cfc, and xmlrpcservice.cfc to the new directory.
  3. Point your browser at the Dumpleton Software Consulting debugger:
    http://www.dscpl.com.au/xmlrpc-debugger.php
  4. Enter http://yourserver/rpctest/date.cfc?method=xmlrpc&paramNames=date in the URL field.
  5. Enter setDate in the Method field.
  6. Enter ("01/01/1999") in the Parameters field. Be sure to include the parentheses.
  7. Click the Execute button.

After the XML-RPC debugger finishes processing, you'll see the results of your request, the XML representation of the request, and the raw response from your server in the Results field.

Calling an Existing XML-RPC Service

Here's a real-world example of using ColdFusion MX and the XRF as an XML-RPC client. Most blogging apps support update notification using Weblogs.com. The idea is that every time you post a new entry, you send a request to the Weblogs.com server, which in turn verifies that you have indeed added new content. It then adds your site to a changes.xml file, which many notification and search services use to keep track of fresh blog content.

If your ColdFusion-based blog isn't sending update pings, here's how to do it:

<cfset myCall = ArrayNew(1) />
<cfset myCall[1] = "weblogUpdates.ping" />
<cfset myCall[2] = XmlFormat("My Blog Title") />
<cfset myCall[3] = XmlFormat("http://yourserver/blogpath/") />
<cfinvoke component="xmlrpc"
   method="CFML2XMLRPC"
   returnvariable="myXml"
   data="#mycall#"
   type="call" />
<cfhttp method="POST" url="http://rpc.weblogs.com/RPC2" useragent="myBloggingApp">
   <cfhttpparam name="param1" value="<?xml version=""1.0""?>#myxml#" type="XML" />
</cfhttp>

What's going on here? First you establish a simple array that contains the information necessary for your call to Weblogs.com. This includes the name of the desired XML-RPC method ("weblogUpdates.ping"), the title of the newly updated blog ("My Blog Title"), and your blog's URL ("http://yourserver..."). Next this array is fed to xmlrpc.cfc, which converts it to a valid XML-RPC request package. From there, it's simply a matter of sending a CFHTTP POST to the appropriate URL with our new package as the payload.

If it's important for you to know the results of your ping, just give xmlrpc.cfc a chance to parse the response:

Understanding the XRF Plumbing

Let’s examine the two CFCs that comprise the Framework and their various methods. In the process, you’ll also get a look at some example XML-RPC packages and the ColdFusion code that creates them.

xmlrpcservice.cfc

This ColdFusion component has a single method called xmlrpc. However, it isn't intended to be called as a stand-alone component; it serves as a wrapper for other CFCs. To use it, you need to make two additions to an existing component:

  1. Set the component to extends="xmlrpcservice".
  2. Add xmlRpcAccess="true" to each method that you would like to expose using XML-RPC. For security reasons, xmlrpcservice.cfc will refuse to call a method that is not so identified.

So given a CFC like this...

<cfcomponent extends="xmlrpcservice">
   <cffunction name="setUser" output="false" access="remote">
      <cfreturn true />
   </cffunction>
   <cffunction name="getUser" output="false" access="remote" xmlRpcAccess="true">
      <cfreturn false />
   </cffunction>
</cfcomponent>

...you can see that, while both methods are available to remote SOAP access, only the getUser method is available to XML-RPC clients.

To call the XML-RPC service, add a couple key/value pairs to the URL's query string:

  • ?method=xmlrpc : This switches your component into "XML-RPC mode."
  • &paramNames=foo|bar|foobar : By default, XML-RPC variables are unnamed unless they are members of a struct, and are normally accessed as an array of ordered parameters. This can be a problem for ColdFusion MX developers because CFCs frequently expect named arguments. To solve this problem, set the paramNames key to a pipe-delimited list of argument names.

So given a CFC like this...

<cfcomponent extends="xmlrpcservice">
   <cffunction name="setUser" output="false" access="remote" xmlRpcAccess="true">
      <cfargument name="name" />
      <cfargument name="type" />
      <cfargument name="title" />

      ...

      <cfreturn myResponse />
   </cffunction>
</cfcomponent>

and an XML-RPC request like this...

<?xml version="1.0"?>
<methodCall>
   <methodName>setUser</methodName>
   <params>
      <param>
         <value><string>John Q. User</string></value>
      </param>
      <param>
         <value><int>13</int></value>
      </param>
      <param>
         <value><string>Office Manager</string></value>
      </param>
   </params>
</methodCall>

...you would need to construct a URL that looks something like this:

http://yourserver/user.cfc?method=xmlrpc&paramNames=name|type|title

If for some reason the order of the parameters in the XML-RPC request were to change, the order of the names in the paramNames list would need to change as well.

xmlrpc.cfc

This ColdFusion component has two primary methods: XMLRPC2CFML and CFML2XMLRPC. In many cases you'll have no need to call either of them because the xmlrpcservice component handles all the details of responding to XML-RPC requests for you. But if you're building an XML-RPC client application or want to use XML-RPC outside the XRF, you'll need to know how it works.

To convert an incoming XML-RPC package to a CFML data structure, call the XMLRPC2CFML method:

<cfinvoke component="xmlrpc"
   method="XMLRPC2CFML"
   returnvariable="myRequest"
   data="#GetHttpRequestData().content#" />

Given an incoming package like this...

<?xml version="1.0"?>
<methodCall>
   <methodName>examples.getStateName</methodName>
   <params>
      <param>
         <value><i4>41</i4></value>
         </param>
      </params>
   </methodCall>

...you will end up with this myRequest structure (see Figure 1):


Figure 1. The converted XML-RPC package.

Converting CFML to XML-RPC is a bit more complicated, for two reasons:

  1. There are three different kinds of XML-RPC packages: call, response, and responsefault. Each has different formatting requirements so you must specify the type of package when calling the component.
  2. CFML is a loosely typed language, which can cause problems in situations where the XML-RPC client or server on the other end of a request expects data to be returned in a specific format.

Let's address the different package types first. All data passed to xmlrpc.cfc must be part of an array. The contents of that array depend upon the package type.

Package type="call"

<cfset myCall = ArrayNew(1) />
<cfset myCall[1] = "methodName" />
<cfset myCall[2] = 123 />
<cfset myCall[3] = StructNew() />
<cfset myCall[3].foo = "this is a member of a struct" />
<cfset myCall[3].bar = "so is this" />
<cfinvoke component="xmlrpc"
   method="CFML2XMLRPC"
   returnvariable="myXml"
   type="call"
   data="#myCall#" />

When the type is set to "call" the first element of the array should contain the name of the method being called. Subsequent array elements become individual parameters in the XML-RPC package. The above example would produce a package like this:

<methodCall>
  <methodName>methodName</methodName>
  <params>
    <param>
      <value>
        <double>123</double>
      </value>
    </param>
    <param>
      <value>
        <struct>
          <member>
            <name>FOO</name>
            <value>
              <string>this is a member of a struct</string>
            </value>
          </member>
          <member>
            <name>BAR</name>
            <value>
              <string>so is this</string>
            </value>
          </member>
        </struct>
      </value>
    </param>
  </params>
</methodCall>

Package type="response"

<cfset myResponse = ArrayNew(1) />
<cfset myResponse[1] = StructNew() />
<cfset myResponse[1].foo = "this is a member of a struct" />
<cfset myResponse[1].bar = "so is this" />
<cfinvoke component="xmlrpc"
   method="CFML2XMLRPC"
   returnvariable="myXml"
   type="response"
   data="#myResponse#" />

When the type is set to "response" all array elements are converted to individual parameters. Note that the XML-RPC specification expects a single parameter in a response, so you should only have one element in your array in most cases:

<methodResponse>
  <params>
    <param>
      <value>
        <struct>
          <member>
            <name>FOO</name>
            <value>
              <string>this is a member of a struct</string>
            </value>
          </member>
          <member>
            <name>BAR</name>
            <value>
              <string>so is this</string>
            </value>
          </member>
        </struct>
      </value>
    </param>
  </params>
</methodResponse>

Package type="responsefault"

<cfset myResponse = ArrayNew(1) />
<cfset myResponse[1] = 14 />
<cfset myResponse[2] = "An error has occurred." />
<cfinvoke component="xmlrpc"
   method="CFML2XMLRPC"
   returnvariable="myXml"
   type="response"
   data="#myResponse#" />

When the type is set to "responsefault" the array should have two elements. The first is set to a numeric error code; the second is set to a string describing the error. Here are the results of the example:

<methodResponse>
  <fault>
    <value>
      <struct>
        <member>
          <name>faultCode</name>
          <value><int>14</int></value>
        </member>
        <member>
          <name>faultString</name>
          <value>
            <string>An error has occurred.</string>
          </value>
        </member>
      </struct>
    </value>
  </fault>
</methodResponse>

Variable Types

Now we address the issue of variable types. You may never encounter a problem in this area; you may never need to even think about it. But if you do, here's what you need to know.

Let's imagine a package you're creating:

<cfset myCall = ArrayNew(1) />
<cfset myCall[1] = "getUser" />
<cfset myCall[2] = "Bob" />
<cfset myCall[3] = "true" />
<cfinvoke component="xmlrpc"
   method="CFML2XMLRPC"
   returnvariable="myXml"
   type="call"
   data="#myResponse#" />

Here's the problem. Imagine that the service you're accessing considers it important that the second parameter (called myCall[3]) be a string, not a Boolean. Because of the way ColdFusion manages variables, there is no way for xmlrpc.cfc to figure out on its own that you want "true" to mean "<string>true</string>." Left to its own devices, the component will convert "true" to "<boolean>true</boolean>," triggering an error from the service you're calling.

To force individual variables to be serialized as a given type, you need to prepend a token to each "problem" parameter with the token corresponding to a variable type defined in the XML-RPC specification. Using the above example, you end up with this:

<cfset myCall = ArrayNew(1) />
<cfset myCall[1] = "getUser" />
<cfset myCall[2] = "Bob" />
<cfset myCall[3] = "(string)" & "true" />
<cfinvoke component="xmlrpc"
   method="CFML2XMLRPC"
   returnvariable="myXml"
   type="call"
   data="#myResponse#" />

Valid tokens include the following:

  • (i4) or (int) or $i4 or $int
  • (boolean) or $boolean
  • (string) or $string
  • (double) or $double
  • (dateTime.iso8601) or $dateTime.iso8601

Fortunately, you don't need to use a token to accurately identify binary, array, or struct variables.

Using the XML-RPC Framework

Not every web service needs an XML-RPC interface. Two ColdFusion applications talking to one another behind a corporate firewall, for example, really won't benefit from the XML-RPC Framework. Native SOAP support does the job just fine.

But if your applications are exposed to the Internet at large, XML-RPC support can be a big help. After all, not every developer has access to the tools that Macromedia has given you in ColdFusion MX. Using the XRF may broaden your audience in ways you never expected.


About the Author

Roger Benningfield is a ColdFusion developer specializing in online community applications. He is the author of the JournURL blog/discussion application for ColdFusion MX as well as the hosting service of the same name. You can catch up with him at Big Damn Heroes, the home of his personal and professional web logs.